<?php

/**
 * ApplePay Validation
 **/
class iap
{
    /**
     * 验证iAP信息
     * @param string $receipt
     * @param int $timeout
     * @param boolean $isSandbox
     */
    public function getReceiptData($receipt, $timeout = 15, $isSandbox = FALSE)     
    {
        $result = [];

        // 验证地址
        $endpoint = 'https://buy.itunes.apple.com/verifyReceipt';  
        $isSandbox && $endpoint = 'https://sandbox.itunes.apple.com/verifyReceipt';     

        $postData = json_encode(
            array('receipt-data' => $receipt)
        );

        $ch = curl_init($endpoint);     
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);     
        curl_setopt($ch, CURLOPT_POST, true);     
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
        curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        $response = curl_exec($ch);     
        $errno    = curl_errno($ch);     
        $errmsg   = curl_error($ch);     
        curl_close($ch);     

        if(!$errno)
        {     
            $data = json_decode($response, TRUE);  

            if(is_array($data) && isset($data['status']) && $data['status'] == 0)
            {
                $data = $data['receipt'];
                $result = [     
                    'quantity' => $data['in_app'][0]['quantity'], 
                    'product_id' => $data['in_app'][0]['product_id'],   
                    'transaction_id' => $data['in_app'][0]['transaction_id'],
                    'purchase_date' => $data['in_app'][0]['purchase_date'], 
                ];     
            }
        }         

        return $result;
    }
}
